package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.ActivityException;
import com.baidu.iit.pvm.PvmEventConstacts;
import com.baidu.iit.pvm.delegate.SubProcessActivityBehavior;
import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pvm.process.ScopeImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流程结束时触发的END动作
 *
 * @ThreadSafe
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationProcessEnd extends AbstractEventAtomicOperation {

    private static Logger logger = LoggerFactory.getLogger(AtomicOperationProcessEnd.class);

    @Override
    protected ScopeImpl getScope(InterpretableExecution execution) {
        return execution.getProcessDefinition();
    }

    @Override
    protected String getEventName() {
        return PvmEventConstacts.EVENTNAME_END;
    }

    @Override
    protected void eventNotificationsCompleted(InterpretableExecution execution) {
        InterpretableExecution superExecution = execution.getSuperExecution();
        SubProcessActivityBehavior subProcessActivityBehavior = null;

        //在子流程销毁前拷贝相关的变量信息
        if (superExecution!=null) {
            ActivityImpl activity = (ActivityImpl) superExecution.getActivity();
            subProcessActivityBehavior = (SubProcessActivityBehavior) activity.getActivityBehavior();
            try {
                subProcessActivityBehavior.completing(superExecution, execution);
            } catch (RuntimeException e) {
                logger.error("在完成子流程的操作时发生异常:{}", execution, e);
                throw e;
            } catch (Exception e) {
                logger.error("在完成子流程的操作时发生异常:{}", execution, e);
                throw new ActivityException("在完成子流程的操作时发生异常" + execution, e);
            }
        }

        execution.destroy();
        execution.remove();
        if (superExecution!=null) {
            superExecution.setSubProcessInstance(null);
            try {
                subProcessActivityBehavior.completed(superExecution);
            } catch (RuntimeException e) {
                logger.error("在完成子流程的操作时发生异常:{}", execution, e);
                throw e;
            } catch (Exception e) {
                logger.error("在完成子流程的操作时发生异常:{}", execution, e);
                throw new ActivityException("在完成子流程的操作时发生异常 " + execution, e);
            }
        }
    }
}
